import peewee as pw

from db.base_model import BaseModel


class Version(BaseModel):
    version_number = pw.CharField()
    release_date = pw.DateField()
    update_content = pw.TextField()

    class Meta:
        table_name = "version"

    # 获取所有版本信息
    @classmethod
    def get_all_versions(cls, page_size, page_number):
        limit = page_size
        offset = (page_number - 1) * page_size
        versions = cls.select()
        total = versions.count()
        res = versions.order_by(cls.id).offset(offset).limit(limit)
        versions_data = [cls.version_to_dict(version) for version in res]
        return total, versions_data

    # 获取单个版本信息
    @classmethod
    def get_version(cls, version_id):
        try:
            version = cls.get(cls.id == version_id)
            return cls.version_to_dict(version)
        except cls.DoesNotExist:
            return None

    # 创建新版本信息
    @classmethod
    def create_version(cls, version_data):
        version = cls.create(**version_data)
        return cls.version_to_dict(version)

    # 更新版本信息
    @classmethod
    def update_version(cls, version_id, updated_data):
        version = cls.get(cls.id == version_id)
        version.version_number = updated_data.get(
            "version_number", version.version_number
        )
        version.release_date = updated_data.get("release_date", version.release_date)
        version.update_content = updated_data.get(
            "update_content", version.update_content
        )
        version.save()
        return cls.version_to_dict(version)

    # 删除版本信息
    @classmethod
    def delete_version(cls, version_id):
        try:
            version = cls.get(cls.id == version_id)
            version.delete_instance()
            return True
        except cls.DoesNotExist:
            return False

    # 辅助函数：将版本模型转换为字典
    @classmethod
    def version_to_dict(cls, version):
        return {
            "id": version.id,
            "version_number": version.version_number,
            "release_date": version.release_date,
            "update_content": version.update_content,
        }


class VersionReachUser(BaseModel):
    version_id = pw.IntegerField(null=False)
    user_id = pw.CharField(max_length=128, null=False)

    class Meta:
        table_name = "version_reach_user"
